package pagerouter

import (
	"fmt"
	"net/http"
	"path"
	"text/template"

	"gitee.com/chenrh/ios-local/AppDdistribute/libs"
)

func UploadForm(w http.ResponseWriter, r *http.Request) {

	viewdata := map[string]interface{}{}

	appnames := libs.AppNames()
	viewdata["appnames"] = appnames

	t, _ := template.ParseFiles("./views/app-upload.html")
	t.Execute(w, viewdata)
}

func Upload(w http.ResponseWriter, r *http.Request) {

	// 32.MB
	r.Body = http.MaxBytesReader(w, r.Body, 32*libs.MB)

	password := r.FormValue("password")

	if password != "uptest2023" {
		w.Write([]byte("密码不正确"))
		return
	}

	uploadfile, fileHeader, err := r.FormFile("file")
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}
	defer uploadfile.Close()

	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	extn := path.Ext(fileHeader.Filename)
	if extn != ".ipa" && extn != ".apk" {
		str := fmt.Sprintf("上传失败: %s 不允许上传!", extn)
		w.Write([]byte(str))
		return
	}

	helper := libs.NewAppUploadHelper()
	err = helper.SavaAs(uploadfile, fileHeader.Filename)
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	w.Write([]byte("<script>setTimeout(function(){ window.location.replace('/')}, 2000)</script>"))
	w.Write([]byte("上传成功: " + fileHeader.Filename + " 已上传到服务器!"))
}
